package com.obradovicnjegovan.webprodavnica.dao;

import java.io.Serializable;
import java.util.List;

import org.apache.tapestry5.ioc.annotations.Inject;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

public class HibernateDaoImpl implements HibernateDao {
	@Inject
	private Session session;

	public void setSession(Session session) {
		this.session = session;
	}

	public Session getSession() {
		return session;
	}

	@SuppressWarnings("unchecked")
	public <T> List<T> get(Class<T> searchForType) {
		Session session = getSession();
		Criteria criteria = session.createCriteria(searchForType);
		return criteria.list();
	}

	@SuppressWarnings("unchecked")
	public <T> T get(Serializable id, Class<T> searchForType) {
		Session session = getSession();
		Criteria criteria = session.createCriteria(searchForType);
		criteria.add(Restrictions.idEq(id)).setMaxResults(1);
		return (T) criteria.list().get(0);
	}
	
	@SuppressWarnings("unchecked")
	public <T> List<T> getDescOrder(Class<T> searchForType, String propertyName, int maxvalue) {
		Session session = getSession();
		Criteria criteria = session.createCriteria(searchForType).addOrder(Order.desc(propertyName)).setMaxResults(maxvalue);
		return criteria.list();
	}

	public void save(Object object) {
		Session session = getSession();
		session.saveOrUpdate(object);
	}

	public void delete(Object object) {
		Session session = getSession();
		session.delete(object);
	}

	@SuppressWarnings("rawtypes")
	public void deleteAll(Class clazz) {
		Session session = getSession();
		session.delete("from " + clazz.getName());
	}

	public void flush() {
		Session session = getSession();
		session.flush();
	}
}
